import { CommandType } from '../../battle/Enums'
import { CommandParam, CommandParamMap } from '../../battle/Model'
import { LOG } from '../../ConsoleLogCtrl'
/**
 * 命令状态枚举
 */
export enum CommandManagerState {
    /** 暂停状态 - 只接收不分发 */
    PAUSED = 'paused',
    /** 播放状态 - 接收并分发命令 */
    PLAYING = 'playing'
}

/**
 * 单个命令数据项
 */
export interface SingleCommand {
    /** 命令类型 */
    type: CommandType;
    /** 命令数据 */
    data?: CommandParam<keyof CommandParamMap>;
    /** 接收时间戳 */
    timestamp: number;
    /** 命令ID */
    id: string;
}

/**
 * 回合命令数据
 */
export interface RoundCommands {
    /** 回合编号 */
    roundNumber: number;
    /** 该回合的所有命令 */
    commands: SingleCommand[];
    /** 回合创建时间戳 */
    timestamp: number;
}

/**
 * 命令分发回调函数类型
 */
export type CommandDispatchCallback = (cmd: CommandType, data?: CommandParam<keyof CommandParamMap>) => void;

/**
 * 回合分发回调函数类型
 */
export type RoundDispatchCallback = (round: RoundCommands) => void;

/**
 * 玩家回合命令提交回调函数类型
 */
export type PlayerRoundSubmitCallback = (playerCommands: CommandParam<keyof CommandParamMap>[]) => { success: boolean; error?: string };

/**
 * 战斗命令管理器
 * 负责接收、存储和分发战斗命令，支持暂停/播放状态控制
 */
export class CommandManager {

    /** 单例实例 */
    private static _instance: CommandManager | null = null;

    /** 当前状态 */
    private _state: CommandManagerState = CommandManagerState.PLAYING;

    /** 回合命令队列 */
    private _roundQueue: RoundCommands[] = [];

    /** 命令分发回调函数列表 */
    private _dispatchCallbacks: CommandDispatchCallback[] = [];

    /** 玩家回合命令提交回调函数列表 */
    private _playerRoundSubmitCallbacks: PlayerRoundSubmitCallback[] = [];

    /** 接收回合计数器 */
    private _roundCounter: number = 0;

    /** 接收命令ID计数器 */
    private _commandIdCounter: number = 0;

    /** 检查接收新回合的定时器 */
    private _checkNewCommandsTimer: number | null = null;

    /** 最后一次接收命令的时间戳 */
    private _lastCommandReceivedTime: number = 0;

    /** 战斗结束超时时间（毫秒），默认1分钟 */
    private _battleEndTimeout: number = 60000;

    /** 播放定时器 */
    private _playTimer: number | null = null;

    /** 当前播放的回合索引 */
    private _currentPlayIndex: number = 0;

    /** 当前播放回合内的命令索引 */
    private _currentCommandIndex: number = 0;

    /** 暂停时保存的回合索引 */
    private _pausedRoundIndex: number = 0;

    /** 暂停时保存的命令索引 */
    private _pausedCommandIndex: number = 0;

    /** 播放间隔时间（毫秒） */
    private _playInterval: number = 50;

    /** 最大回合数 */
    private _maxRoundNumber: number = 0;

    /** 所有回合的总命令数 */
    private _totalCommandCount: number = 0;

    /** 是否处于快进模式（不渲染） */
    private _isFastForwarding: boolean = false;

    /**
     * 获取单例实例
     */
    public static getInstance(): CommandManager {
        if (!CommandManager._instance) {
            CommandManager._instance = new CommandManager();
        }
        return CommandManager._instance;
    }

    /**
     * 私有构造函数，确保单例模式
     */
    private constructor() {
        LOG.log('CommandManager 初始化');
        this._lastCommandReceivedTime = Date.now();
    }

    /**
     * 销毁管理器，清理资源
     */
    public destroy(): void {
        this._stopTimedDispatch();
        this._stopCheckNewCommands();
        this._roundQueue = [];
        this._dispatchCallbacks = [];
        this._playerRoundSubmitCallbacks = [];
        this._commandIdCounter = 0;
        this._roundCounter = 0;
        this._currentPlayIndex = 0;
        this._currentCommandIndex = 0;
        this._pausedRoundIndex = 0;
        this._pausedCommandIndex = 0;
        this._lastCommandReceivedTime = 0;
        this._maxRoundNumber = 0;
        this._totalCommandCount = 0;
        CommandManager._instance = null;
        LOG.log('CommandManager 已销毁');
    }

    /**
     * 清空所有命令数据（用于重新加载战斗数据）
     */
    public clearAllCommands(): void {
        LOG.log('CommandManager 开始清空所有命令数据');

        // 停止当前播放和检查
        this._stopTimedDispatch();
        this._stopCheckNewCommands();

        // 清空回合队列
        this._roundQueue = [];

        // 重置计数器和索引
        this._commandIdCounter = 0;
        this._roundCounter = 0;
        this._currentPlayIndex = 0;
        this._currentCommandIndex = 0;
        this._pausedRoundIndex = 0;
        this._pausedCommandIndex = 0;
        this._maxRoundNumber = 0;
        this._totalCommandCount = 0;

        // 更新最后命令接收时间
        this._lastCommandReceivedTime = Date.now();

        LOG.log('CommandManager 所有命令数据已清空');
    }

    /**
     * 设置管理器状态
     * @param state 新状态
     */
    public setState(state: CommandManagerState): void {
        const oldState = this._state;
        this._state = state;
        LOG.log(`CommandManager 状态变更: ${oldState} -> ${state} 当前回合索引:${this._currentPlayIndex},命令索引: ${this._currentCommandIndex}`);

        // 如果从播放切换到暂停，保存当前播放位置并停止定时器
        if (oldState === CommandManagerState.PLAYING && state === CommandManagerState.PAUSED) {
            this._pausedRoundIndex = this._currentPlayIndex;
            this._pausedCommandIndex = this._currentCommandIndex;
            this._stopTimedDispatch();
            this._stopCheckNewCommands();
            LOG.log(`CommandManager 暂停时保存位置 - 回合索引: ${this._pausedRoundIndex}, 命令索引: ${this._pausedCommandIndex}`);
        }

        // 如果切换到播放状态
        if (state === CommandManagerState.PLAYING) {
            // 如果是从暂停状态恢复，则恢复到保存的位置
            if (oldState === CommandManagerState.PAUSED) {
                this._currentPlayIndex = this._pausedRoundIndex;
                this._currentCommandIndex = this._pausedCommandIndex;
                LOG.log(`CommandManager 从暂停恢复播放 - 回合索引: ${this._currentPlayIndex}, 命令索引: ${this._currentCommandIndex}`);
            } else {
                LOG.log(`CommandManager 开始播放 - 回合索引: ${this._currentPlayIndex}, 命令索引: ${this._currentCommandIndex}`);
            }
            this._startTimedDispatch();
            this._startCheckNewCommands();
        }
    }

    /**
     * 获取当前状态
     */
    public getState(): CommandManagerState {
        return this._state;
    }

    /**
     * 开始检查新命令
     * 定期检查是否有新命令可播放，以及是否超时
     */
    private _startCheckNewCommands(): void {
        if (this._checkNewCommandsTimer !== null) {
            return; // 已经在检查中
        }

        LOG.log('CommandManager 开始检查新命令');

        // 每秒检查一次是否有新命令可播放
        this._checkNewCommandsTimer = setInterval(() => {
            // 检查是否超时（1分钟没有接收到新命令）
            const currentTime = Date.now();
            const timeSinceLastCommand = currentTime - this._lastCommandReceivedTime;

            if (timeSinceLastCommand > this._battleEndTimeout) {
                LOG.log(`CommandManager 超过${this._battleEndTimeout / 1000}秒未接收到新命令，认为战斗已结束`);
                // 如果超时，停止检查
                this._stopCheckNewCommands();
                return;
            }

            // 如果当前没有播放，但有新命令可播放，则开始播放
            if (this._state === CommandManagerState.PLAYING && this._playTimer === null) {
                const { totalCommands, playedCommands } = this.calculateCommandCounts();

                // 如果还有未播放的命令，开始播放
                if (playedCommands < totalCommands) {
                    LOG.log('CommandManager 检测到新命令，开始播放');
                    this._startTimedDispatch();
                }
            }
        }, 1000); // 每秒检查一次
    }

    /**
     * 停止检查新命令
     */
    private _stopCheckNewCommands(): void {
        if (this._checkNewCommandsTimer !== null) {
            clearInterval(this._checkNewCommandsTimer);
            this._checkNewCommandsTimer = null;
            LOG.log('CommandManager 停止检查新命令');
        }
    }

    /**
     * 生成唯一的命令ID
     */
    private _generateCommandId(): string {
        return `cmd_${++this._commandIdCounter}`;
    }

    /**
     * 接收战斗命令
     * @param cmd 命令类型
     * @param data 命令数据
     */
    public receiveCommand(cmd: CommandType, data?: CommandParam<keyof CommandParamMap>): void {
        // 更新最后命令接收时间
        this._lastCommandReceivedTime = Date.now();

        const singleCommand: SingleCommand = {
            timestamp: this._lastCommandReceivedTime,
            type: cmd,
            data: data,
            id: this._generateCommandId()
        };
        // 获取命令的回合数，如果没有则使用当前回合计数器+1
        const roundNumber = data?.round ?? null;

        if (roundNumber == null || roundNumber == undefined){
            LOG.error("CommandManager 命令回合数不能为空");
        }

        // 查找是否已存在该回合的命令组
        let targetRound = this._roundQueue.find(round => round.roundNumber === roundNumber);

        if (!targetRound) {
            // 如果该回合不存在，创建新的回合命令组
            targetRound = {
                roundNumber: roundNumber,
                commands: [],
                timestamp: this._lastCommandReceivedTime
            };

            // 将新回合插入到正确的位置（按回合号排序）
            const insertIndex = this._roundQueue.findIndex(round => round.roundNumber > roundNumber);
            if (insertIndex === -1) {
                this._roundQueue.push(targetRound);
            } else {
                this._roundQueue.splice(insertIndex, 0, targetRound);
            }

            // 更新回合计数器
            if (roundNumber > this._roundCounter) {
                this._roundCounter = roundNumber;
            }
        }

        // 将命令添加到对应回合
        targetRound.commands.push(singleCommand);
        LOG.log(`CommandManager 接收命令:${cmd}, ID:${singleCommand.id}, 回合:${roundNumber}, 命令:${targetRound.commands.length}`);

        // 如果处于播放状态，检查是否需要开始播放
        if (this._state === CommandManagerState.PLAYING) {
            // 如果是初始化命令，立即开始播放
            if (cmd === CommandType.init) {
                this._playTimer = setTimeout(() => {
                    this._dispatchNextCommand();
                }, 0);
            }
            // 如果当前没有播放，但有新命令可播放，则开始播放
            else if (this._playTimer === null) {
                const { totalCommands, playedCommands } = this.calculateCommandCounts();

                // 如果还有未播放的命令，开始播放
                if (playedCommands < totalCommands) {
                    this._startTimedDispatch();
                }
            }
        }
        if (cmd === CommandType.end) {
            this._calculateFinalStatistics();
        }
    }

    /**
     * 批量接收命令（用于战报回放等场景）
     * @param commands 命令数组
     */
    public receiveCommandBatch(commands: CommandParam<keyof CommandParamMap>[]): void {
        LOG.log(`CommandManager 批量接收 ${commands.length} 个命令`);

        // 暂停当前播放状态
        this.pause();

        // 批量处理所有命令
        for (let i = 0; i < commands.length; i++) {
            const command = commands[i];

            // 更新最后命令接收时间
            this._lastCommandReceivedTime = Date.now();

            const singleCommand: SingleCommand = {
                timestamp: this._lastCommandReceivedTime,
                type: command.type,
                data: command,
                id: this._generateCommandId()
            };

            // 获取命令的回合数
            const roundNumber = command.round ?? null;

            if (roundNumber == null || roundNumber == undefined) {
                LOG.error(`CommandManager 批量命令第${i+1}个命令回合数不能为空`);
                continue;
            }

            // 查找是否已存在该回合的命令组
            let targetRound = this._roundQueue.find(round => round.roundNumber === roundNumber);

            if (!targetRound) {
                // 如果该回合不存在，创建新的回合命令组
                targetRound = {
                    roundNumber: roundNumber,
                    commands: [],
                    timestamp: this._lastCommandReceivedTime
                };

                // 将新回合插入到正确的位置（按回合号排序）
                const insertIndex = this._roundQueue.findIndex(round => round.roundNumber > roundNumber);
                if (insertIndex === -1) {
                    this._roundQueue.push(targetRound);
                } else {
                    this._roundQueue.splice(insertIndex, 0, targetRound);
                }

                // 更新回合计数器
                if (roundNumber > this._roundCounter) {
                    this._roundCounter = roundNumber;
                }
            }

            // 将命令添加到对应回合
            targetRound.commands.push(singleCommand);

            // 如果是结束命令，计算最终统计
            if (command.type === CommandType.end) {
                this._calculateFinalStatistics();
            }
        }

        LOG.log(`CommandManager 批量接收完成，共处理 ${commands.length} 个命令，当前回合队列长度: ${this._roundQueue.length}`);
    }

    /**
     * 注册命令分发回调函数
     * @param callback 回调函数
     */
    public registerDispatchCallback(callback: CommandDispatchCallback): void {
        this._dispatchCallbacks.push(callback);
        LOG.log(`CommandManager 注册分发回调, 当前回调数量: ${this._dispatchCallbacks.length}`);
    }

    /**
     * 移除命令分发回调函数
     * @param callback 要移除的回调函数
     */
    public unregisterDispatchCallback(callback: CommandDispatchCallback): void {
        const index = this._dispatchCallbacks.indexOf(callback);
        if (index > -1) {
            this._dispatchCallbacks.splice(index, 1);
            LOG.log(`CommandManager 移除分发回调, 当前回调数量: ${this._dispatchCallbacks.length}`);
        }
    }

    /**
     * 注册玩家回合命令提交回调函数
     * @param callback 回调函数
     */
    public registerPlayerRoundSubmitCallback(callback: PlayerRoundSubmitCallback): void {
        this._playerRoundSubmitCallbacks.push(callback);
        LOG.log(`CommandManager 注册回合提交回调, 当前回调数量: ${this._playerRoundSubmitCallbacks.length}`);
    }

    /**
     * 移除玩家回合命令提交回调函数
     * @param callback 要移除的回调函数
     */
    public unregisterPlayerRoundSubmitCallback(callback: PlayerRoundSubmitCallback): void {
        const index = this._playerRoundSubmitCallbacks.indexOf(callback);
        if (index > -1) {
            this._playerRoundSubmitCallbacks.splice(index, 1);
            LOG.log(`CommandManager 移除回合提交回调, 当前回调数量: ${this._playerRoundSubmitCallbacks.length}`);
        }
    }

    /**
     * 提交玩家回合命令集（新的回合制接口）
     * @param playerCommands 玩家回合命令数组
     * @returns 提交结果
     */
    public submitPlayerCommands(playerCommands: CommandParam<keyof CommandParamMap>[]): { success: boolean; error?: string } {
        const player = playerCommands.length > 0 ? playerCommands[0].player : 'unknown';
        const round = playerCommands.length > 0 ? playerCommands[0].round : 0;
        LOG.log(`CommandManager 收到玩家 ${player} 第 ${round} 回合的 ${playerCommands.length} 个命令`);

        // 调用所有注册的回合提交回调函数
        for (const callback of this._playerRoundSubmitCallbacks) {
            try {
                const result = callback(playerCommands);
                if (!result.success) {
                    LOG.error(`CommandManager 回合命令提交失败: ${result.error}`);
                    return result;
                }
            } catch (error) {
                const errorMsg = `CommandManager 回合提交回调执行失败: ${error}`;
                LOG.error(errorMsg);
                return { success: false, error: errorMsg };
            }
        }

        return { success: true };
    }

    /**
     * 暂停命令分发
     */
    public pause(): void {
        this.setState(CommandManagerState.PAUSED);
    }

    /**
     * 开始/恢复命令分发
     */
    public play(): void {
        this.setState(CommandManagerState.PLAYING);
    }

    /**
     * 重新开始播放（不清空回合队列和统计数据）
     * 只重置播放位置到开头，保留所有命令数据
     */
    public restartPlayback(): void {
        // 暂停当前播放
        this.pause();

        // 重置播放位置到开头
        this._currentPlayIndex = 0;
        this._currentCommandIndex = 0;
        this._pausedRoundIndex = 0;
        this._pausedCommandIndex = 0;

        LOG.log('CommandManager 重新开始播放，保留回合队列和统计数据');
        LOG.log(`当前回合队列长度: ${this._roundQueue.length}, 最大回合数: ${this._maxRoundNumber}, 总命令数: ${this._totalCommandCount}`);

    }

    /**
     * 设置播放位置
     * @param targetPosition 目标位置，包含总命令数和目标命令索引
     */
    public setPlayPosition(targetPosition: number): void {
        if (targetPosition < 0) {
            targetPosition = 0;
        }

        // 暂停当前播放
        const wasPlaying = this._state === CommandManagerState.PLAYING;
        if (wasPlaying) {
            this.pause();
        }

        // 计算目标回合和命令索引
        let targetRoundIndex = 0;
        let targetCommandIndex = 0;
        let commandsCount = 0;

        // 遍历回合队列，找到目标位置对应的回合和命令
        for (let i = 0; i < this._roundQueue.length; i++) {
            const roundCommands = this._roundQueue[i].commands.length;

            if (commandsCount + roundCommands > targetPosition) {
                // 找到目标回合
                targetRoundIndex = i;
                targetCommandIndex = targetPosition - commandsCount;
                break;
            }

            commandsCount += roundCommands;

            // 如果是最后一个回合，且目标位置超出总命令数
            if (i === this._roundQueue.length - 1) {
                targetRoundIndex = i;
                targetCommandIndex = roundCommands;
            }
        }

        // 获取当前播放进度
        let playProgress = this.getPlayProgress();

        // 检查是否需要后退或快进
        if (targetPosition < playProgress.current) {
            // 后退逻辑：从头开始分发命令到目标位置
            LOG.log(`CommandManager 后退到位置 ${targetPosition}，从头开始分发命令`);

            // 先重置播放位置到开头
            this._currentPlayIndex = 0;
            this._currentCommandIndex = 0;

            // 使用快速分发命令到目标位置
            this._dispatchToTargetCommand(targetRoundIndex, targetCommandIndex);
        } else if (targetPosition > playProgress.current) {
            // 快进逻辑：直接从当前位置分发到目标位置
            LOG.log(`CommandManager 快进到位置 ${targetPosition}`);
            this._dispatchToTargetCommand(targetRoundIndex, targetCommandIndex);
        } else {
            // 位置相同，不需要操作
            LOG.log(`CommandManager 位置未变化 ${targetPosition}`);
        }

        // 设置新的播放位置
        this._currentPlayIndex = targetRoundIndex;
        this._currentCommandIndex = targetCommandIndex;
        this._pausedRoundIndex = targetRoundIndex;
        this._pausedCommandIndex = targetCommandIndex;

        LOG.log(`CommandManager 设置播放位置 - 回合索引: ${targetRoundIndex}, 命令索引: ${targetCommandIndex}`);

        // 如果之前是播放状态，恢复播放
        if (wasPlaying) {
            this.play();
        }
    }

    /**
     * 计算命令数量信息
     * @returns 命令数量信息，包括总命令数和已播放命令数
     */
    private calculateCommandCounts(): { totalCommands: number, playedCommands: number } {
        let totalCommands = 0;
        let playedCommands = 0;

        // 计算总命令数
        this._roundQueue.forEach(round => {
            totalCommands += round.commands.length;
        });

        // 计算已播放的命令数
        for (let i = 0; i < this._currentPlayIndex; i++) {
            playedCommands += this._roundQueue[i].commands.length;
        }
        playedCommands += this._currentCommandIndex;

        return { totalCommands, playedCommands };
    }

    /**
     * 获取播放进度
     * @returns 播放进度信息
     */
    public getPlayProgress(): { current: number; total: number; percentage: number; currentRound: number; currentCommand: number; totalRounds: number } {
        const totalRounds = this._roundQueue.length;
        const currentRound = Math.min(this._currentPlayIndex, totalRounds);
        const { totalCommands, playedCommands } = this.calculateCommandCounts();

        const percentage = totalCommands > 0 ? (playedCommands / totalCommands) * 100 : 0;

        return {
            current: playedCommands,
            total: totalCommands,
            percentage: Math.round(percentage * 100) / 100,
            currentRound: currentRound + 1, // 显示从1开始的回合号
            currentCommand: this._currentCommandIndex + 1, // 显示从1开始的命令号
            totalRounds: totalRounds // 添加总回合数，方便外部直接获取
        };
    }

    /**
     * 获取暂停时保存的播放位置
     */
    public getPausedPosition(): { roundIndex: number; commandIndex: number } {
        return {
            roundIndex: this._pausedRoundIndex,
            commandIndex: this._pausedCommandIndex
        };
    }

    /**
     * 开始定时分发命令
     */
    private _startTimedDispatch(): void {
        if (this._playTimer !== null) {
            return; // 已经在播放中
        }

        const { totalCommands, playedCommands } = this.calculateCommandCounts();

        // 如果没有未播放的命令，退出
        if (playedCommands >= totalCommands) {
            LOG.log('CommandManager 所有命令已播放完毕');
            return;
        }

        LOG.log(`CommandManager 开始定时分发命令, 间隔: ${this._playInterval}ms`);
        this._dispatchNextCommand();
    }

    /**
     * 停止定时分发
     */
    private _stopTimedDispatch(): void {
        if (this._playTimer !== null) {
            clearTimeout(this._playTimer);
            this._playTimer = null;
            LOG.log('CommandManager 停止定时分发');
        }
    }

    /**
     * 分发下一个命令
     */
    private _dispatchNextCommand(): void {
        const { totalCommands, playedCommands } = this.calculateCommandCounts();

        // 检查是否还有命令需要播放
        const hasMoreCommands = playedCommands < totalCommands;

        if (!hasMoreCommands) {
            LOG.log('CommandManager 当前所有命令已播放完毕，等待新命令');
            this._stopTimedDispatch();
            return;
        }

        if (this._state !== CommandManagerState.PLAYING) {
            this._stopTimedDispatch();
            return;
        }

        const currentRound = this._roundQueue[this._currentPlayIndex];

        // 检查当前回合是否还有命令需要播放
        if (this._currentCommandIndex >= currentRound.commands.length) {

            // LOG.log(`CommandManager 回合 ${currentRound.roundNumber} 播放完毕，移动到下一回合`);

            // 使用定时器异步处理下一个回合，在定时器回调中才更新索引
            this._playTimer = setTimeout(() => {
                // 在这里才真正移动到下一个回合
                this._currentPlayIndex++;
                this._currentCommandIndex = 0;

                // 计算总命令数和已播放命令数
                const { totalCommands, playedCommands } = this.calculateCommandCounts();

                // 检查是否还有命令需要播放
                const hasMoreCommands = playedCommands < totalCommands;

                if (hasMoreCommands) {
                    this._dispatchNextCommand();
                } else {
                    LOG.log('CommandManager 当前所有命令已播放完毕，等待新命令');
                    this._stopTimedDispatch();
                }
            }, 0);
            return;
        }

        // 分发当前命令
        const command = currentRound.commands[this._currentCommandIndex];
        const currentCommandNumber = this._currentCommandIndex + 1;
        this._dispatchCommand(command);

        LOG.log(`CommandManager 播放回合 ${currentRound.roundNumber} 命令 ${currentCommandNumber}/${currentRound.commands.length}`);

        // 设置下一次分发的定时器
        this._playTimer = setTimeout(() => {
            // 在定时器回调中移动到下一个命令
            this._currentCommandIndex++;
            this._dispatchNextCommand();
        }, this._playInterval);
    }

    /**
     * 分发单个命令
     * @param commandItem 命令项
     */
    private _dispatchCommand(commandItem: SingleCommand): void {
        // 调用所有注册的回调函数
        for (const callback of this._dispatchCallbacks) {
            try {
                callback(commandItem.type, commandItem.data);
            } catch (error) {
                LOG.error(`CommandManager 分发命令时回调函数出错:`, error);
            }
        }
    }

    /**
     * 快速分发命令到指定的回合和命令索引位置
     * @param targetRoundIndex 目标回合索引
     * @param targetCommandIndex 目标命令索引
     */
    private _dispatchToTargetCommand(targetRoundIndex: number, targetCommandIndex: number): void {
        LOG.log(`CommandManager 快速分发命令到 - 回合索引: ${targetRoundIndex}, 命令索引: ${targetCommandIndex}`);

        // 停止当前的定时分发
        this._stopTimedDispatch();

        // 保存当前播放间隔，并设置为0以加速分发
        const oldPlayInterval = this.getPlayInterval();
        this.setPlayInterval(0);

        // 从当前位置开始，快速分发命令直到目标位置
        let currentRoundIndex = this._currentPlayIndex;
        let currentCmdIndex = this._currentCommandIndex;

        // 遍历所有需要分发的命令
        while (currentRoundIndex < this._roundQueue.length) {
            const round = this._roundQueue[currentRoundIndex];

            // 处理当前回合的命令
            while (currentCmdIndex < round.commands.length) {
                // 如果已经到达目标位置，退出循环
                if (currentRoundIndex === targetRoundIndex && currentCmdIndex >= targetCommandIndex) {
                    break;
                }

                // 分发当前命令
                const command = round.commands[currentCmdIndex];
                this._dispatchCommand(command);

                // 移动到下一个命令
                currentCmdIndex++;
            }

            // 如果已经到达目标位置，退出循环
            if (currentRoundIndex === targetRoundIndex && currentCmdIndex >= targetCommandIndex) {
                break;
            }

            // 如果当前回合的命令已经全部分发完，移动到下一个回合
            if (currentCmdIndex >= round.commands.length) {
                currentRoundIndex++;
                currentCmdIndex = 0;
            }
        }

        // 恢复原来的播放间隔
        this.setPlayInterval(oldPlayInterval);

        LOG.log(`CommandManager 快速分发完成 - 当前位置: 回合索引 ${currentRoundIndex}, 命令索引 ${currentCmdIndex}`);
    }

    /**
     * 计算最终统计数据
     * 记录最大回合值和所有回合的总命令数
     */
    private _calculateFinalStatistics(): void {
        // 计算最大回合数
        this._maxRoundNumber = 0;
        this._totalCommandCount = 0;

        for (const round of this._roundQueue) {
            // 更新最大回合数
            this._maxRoundNumber = Math.max(this._maxRoundNumber, round.roundNumber);
            // 累加总命令数
            this._totalCommandCount += round.commands.length;
        }

        LOG.log(`CommandManager 统计完成 - 最大回合数: ${this._maxRoundNumber}, 总命令数: ${this._totalCommandCount}`);

    }

    /**
     * 判断游戏是否已结束
     * @returns 如果游戏已结束返回true，否则返回false
     */
    public isGameEnded(): boolean {
        return this._maxRoundNumber >= 0 && this._totalCommandCount > 0;
    }

    /**
     * 获取最大回合数
     * @returns 最大回合数
     */
    public getMaxRoundNumber(): number {
        return this._maxRoundNumber;
    }

    /**
     * 获取所有回合的总命令数
     * @returns 总命令数
     */
    public getTotalCommandCount(): number {
        return this._totalCommandCount;
    }

    /**
     * 设置播放间隔时间
     * @param interval 间隔时间（毫秒），默认2000ms
     */
    public setPlayInterval(interval: number): void {
        this._playInterval = interval;
        LOG.log(`CommandManager 设置播放间隔: ${interval}ms`);
    }

    /**
     * 获取播放间隔时间
     */
    public getPlayInterval(): number {
        return this._playInterval;
    }

    /**
     * 获取回合队列副本（只读）
     */
    public getRoundQueue(): readonly RoundCommands[] {
        return [...this._roundQueue];
    }

    /**
     * 清空回合队列
     */
    public clearQueue(): void {
        const queueLength = this._roundQueue.length;
        this._roundQueue = [];
        this._currentPlayIndex = 0;
        this._currentCommandIndex = 0;
        this._pausedRoundIndex = 0;
        this._pausedCommandIndex = 0;
        this._roundCounter = 0;
        this._stopTimedDispatch();
        LOG.log(`CommandManager 清空回合队列, 清除了 ${queueLength} 个回合`);
    }

    /**
     * 设置快进模式
     * @param value 是否启用快进模式
     */
    public setFastForwarding(value: boolean): void {
        this._isFastForwarding = value;
        LOG.log(`CommandManager 快进模式: ${value ? '启用' : '禁用'}`);
    }

    /**
     * 获取当前是否处于快进模式
     * @returns 是否处于快进模式
     */
    public isFastForwarding(): boolean {
        return this._isFastForwarding;
    }
}